package com.ys.controller.api.business;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.entity.business.TpAnalysisDailyTargetSet;
import com.ys.entity.business.TpShopRegisterPhaseRecord;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpAnalysisDailyTargetSetService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tpAnalysisDailyTargetSet")
public class ApiInterTpAnalysisDailyTargetSetController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTpAnalysisDailyTargetSetController.class);
    private static Long MENU_ID = 71L;
    private static Long MENU_ID_E = 73L;

    @Autowired
    private CommonApiService<TpAnalysisDailyTargetSet> commonApiService;

    @Autowired
    private TpAnalysisDailyTargetSetService tpAnalysisDailyTargetSetService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TpAnalysisDailyTargetSet setSeachSql(TpAnalysisDailyTargetSet cond,int resultType){
        cond.addField("O.VGsJc AS vGsJc");//运营公司简称
        cond.addField("PO.VGsJc AS pVGsJc");//上级运营公司简称
        //cond.addField("O.VGsBm AS vGsBm");//运营公司编码
        cond.addField("O.CUser + '/' + U.UserName AS operateUser ");//运营人工号/姓名
        cond.addField("UO.DeptName AS vYyJb");//运营组别，所属部门
        cond.addField("CASE WHEN PO.CUser IS NULL THEN '' ELSE PO.CUser + '/' + PU.UserName END pOperateUser ");//上级运营人工号/姓名
        cond.addField("PUO.DeptName AS pVYyJb ");//运营组别上级，所属部门上级
        cond.addField("AR.Name AS regionName ");//店铺区域；countryName国家名称
        cond.addField("S.FirstSaleDay AS firstSaleDay ");//开售日期

        //关联卖家信息表
        cond.addLeftJoin("kjecp.dbo.TP_AmazonSeller SA ON SA.Vgsbm = A.Vgsbm ");
        //关联网店信息表
        cond.addLeftJoin("( SELECT MAX(SA.FirstSaleDay) AS FirstSaleDay, SA.SellerId FROM kjecp.dbo.TP_AmazonShop SA GROUP BY SA.SellerId ) S ON S.SellerId = SA.SellerId");
        //关联网店信息表

        //关联区域信息表
        cond.addLeftJoin("kjecp.dbo.TP_AmazonRegion AR ON AR.Code = SA.RegionCode ");
        //关联运营公司管理表
        cond.addLeftJoin("kjecp.dbo.THR_OperateCompanyApply O ON O.VGsBm = A.VGsBm ");
        cond.addLeftJoin("kjecp.dbo.TS_UserInfo U ON U.UserId = O.Cuser");
        cond.addLeftJoin("kjecp.dbo.TS_OrganizationInfo UO ON UO.Orgid = U.DeptId");

        //关联运营公司管理表-上级
        cond.addLeftJoin("kjecp.dbo.TS_OperateOrg ORG ON ORG.Id = O.OperateOrgId ");
        cond.addLeftJoin("kjecp.dbo.THR_OperateCompanyApply PO ON PO.VGsBm = ORG.HeadVgsbm AND 1=1 ");
        cond.addLeftJoin("kjecp.dbo.TS_UserInfo PU ON PU.UserId = PO.Cuser AND 1=1 ");
        cond.addLeftJoin("kjecp.dbo.TS_OrganizationInfo PUO ON PUO.Orgid = PU.DeptId");

        cond.where("AR.Name IS NOT NULL ");
        //排序
        cond.setOrderby("A.InfoTime DESC,A.VGsBm ASC");

        return  cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate,int resultType){
        List<Map<String, Object>> tableDate = new ArrayList();
        //获取这个月时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String thisMonth = sdf.format(calendar.getTime());//这个月
        int thisMaxDay = new DateUtil().getMonthLastDay(thisMonth);//获取月份的最后一天
        calendar.add(Calendar.MONTH, -1);
        String oldMonth = sdf.format(calendar.getTime());//上个月
        int maxDay = new DateUtil().getMonthLastDay(oldMonth);//获取月份的最后一天
        calendar.add(Calendar.MONTH, -1);
        List<Map<String, Object>> oldMonthOrderList = new ArrayList<>();
        List<Map<String, Object>> thisMonthElaborateOrderList = new ArrayList<>();

        if(resultType==0){//全部
            //统计查询这个月商品订单数据
            oldMonthOrderList = tpAnalysisDailyTargetSetService.searchOldMonthAllOrderList(thisMonth+"-01",thisMonth+"-"+thisMaxDay);
        }else {//精品
            //统计查询这个月的精品订单数据
            thisMonthElaborateOrderList = tpAnalysisDailyTargetSetService.searchOldMonthElaborateOrderList(thisMonth+"-01",thisMonth+"-"+thisMaxDay);
        }
        Predicate<List> listIsNull = listInfo-> listInfo!=null && listInfo.size()>0;

        for(Map<String, Object> setItem:resDate){
            String monthStr = setItem.get("infoTime").toString();
            int lastDay = new DateUtil().getMonthLastDay(monthStr);//获取月份的天数
            int dailyTarget = resultType==0?Integer.parseInt(setItem.get("dailyTarget").toString()):Integer.parseInt(setItem.get("elaborateDailyTarget").toString());//日均目标
            int monthTarget =lastDay*dailyTarget;
            setItem.put("monthTarget",monthTarget);//计算月目标

            if(thisMonth.equals(monthStr)){
                String vGsBm = setItem.get("vGsBm").toString();//运营公司编码
                //累计订单
                int totalOrder = 0;
                //累计目标达成(增长率)
                BigDecimal growthRate = new BigDecimal("0");
                if(resultType==0){
                    if(listIsNull.test(oldMonthOrderList)){
                        //根据shopId过滤上个月的商品订单统计数据
                        List<Map<String, Object>> oldMonthOrderByShop = oldMonthOrderList.stream()
                                .filter(item->item.get("VGsBm").equals(vGsBm))
                                .collect(Collectors.toList());
                        if(oldMonthOrderByShop.size()>0){
                            totalOrder = Integer.parseInt(oldMonthOrderByShop.get(0).get("Num").toString());
                            //计算达成率
                            //获取月目标总数
                            BigDecimal monthTotal = new BigDecimal(monthTarget);
                            //计算达成率
                            BigDecimal oldData = new BigDecimal(totalOrder);
                            growthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }else {
                    if(listIsNull.test(thisMonthElaborateOrderList)){
                        //根据shopId过滤这个月的精品订单统计数据
                        List<Map<String, Object>> thisMonthElaborateOrderListByShop = thisMonthElaborateOrderList.stream()
                                .filter(item->item.get("VGsBm").toString().equals(vGsBm)).collect(Collectors.toList());
                        if(thisMonthElaborateOrderListByShop.size()>0){
                            totalOrder = Integer.parseInt(thisMonthElaborateOrderListByShop.get(0).get("Num").toString());
                            //获取月目标总数
                            BigDecimal monthTotal = new BigDecimal(monthTarget);
                            //计算达成率
                            BigDecimal oldData = new BigDecimal(totalOrder);
                            growthRate =  (BigDecimal.ZERO).compareTo(monthTotal) == 0 ? new BigDecimal("1"):oldData.divide(monthTotal,4,BigDecimal.ROUND_HALF_UP);

                        }
                    }
                }

                //填入累计订单
                setItem.put("orderTotal",totalOrder);
                setItem.put("elaborateOrderTotal",totalOrder);
                //填入累计目标达成(达成率)
                setItem.put("growthRate",growthRate);
                setItem.put("elaborateGrowthRate",growthRate);
            }
            BigDecimal growthRateNum = setItem.get("growthRate")!=null?(BigDecimal) setItem.get("growthRate"):BigDecimal.ZERO;
            BigDecimal elaborateGrowthRateNum = setItem.get("elaborateGrowthRate")!=null?(BigDecimal) setItem.get("elaborateGrowthRate"):BigDecimal.ZERO;
            setItem.put("growthRate",String.format("%.2f", growthRateNum.floatValue()*100)+"%");
            setItem.put("elaborateGrowthRate",String.format("%.2f", elaborateGrowthRateNum.floatValue()*100)+"%");

            tableDate.add(setItem);
        }

        return tableDate;
    }

    //根据类型获取返回数据
    public LayuiTableVoJA searchByType(TpAnalysisDailyTargetSet cond,int resultType){
        cond = setSeachSql(cond,resultType);
        //权限
        if(resultType==0){
    		cond = commonApiService.dataAuth(MENU_ID, cond);
        }else {
    		cond = commonApiService.dataAuth(MENU_ID_E, cond);
        }

        LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
        //获取
        JSONArray tableVoJAData = tableVoJA.getData();
        //转换
        List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
        List<Map<String, Object>> resListNew = new ArrayList();
        resList.forEach(item-> resListNew.add(item));

        //处理数据
        resList = setList(resListNew,0);
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
        tableVoJA.setData(jsonArray);
        return tableVoJA;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tpAnalysisDailyTargetSet:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TpAnalysisDailyTargetSet cond
    ){
        try {
            return searchByType(cond,0);
        }catch (Exception e){
            logger.error("查询运营日报目标维护表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 查询
     */
    //@RequiresPermissions("tpAnalysisDailyTargetSet:view")
    @RequestMapping("/searchByElaborate")
    @ResponseBody
    public LayuiTableVoJA searchByElaborate(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TpAnalysisDailyTargetSet cond
    ){
        try {
            return searchByType(cond,1);
        }catch (Exception e){
            logger.error("查询运营日报目标维护表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    //根据类型获取返回导出数据
    public UploadDto exportByType(TpAnalysisDailyTargetSet cond,int setType){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,setType);
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            listData = setList(listData,setType);

            Long menuId = setType==0?MENU_ID:MENU_ID_E;

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();

            ExportExcelUtils<TpShopRegisterPhaseRecord> util = new ExportExcelUtils<>(new TpShopRegisterPhaseRecord());

            String toFilePath = util.exportExcel(listData, listField, "运营日报目标维护表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return dto;
        }catch (Exception e){
            logger.error("导出运营日报目标维护表出错：",e.getMessage(),e);
            return null;
        }

    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TpAnalysisDailyTargetSet cond){
        try {
            UploadDto dto =exportByType(cond,0);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出运营日报目标维护表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/exportByElaborate")
    @ResponseBody
    public R exportByElaborate(@ModelAttribute TpAnalysisDailyTargetSet cond){
        try {
            UploadDto dto =exportByType(cond,1);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出运营日报目标维护表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 设置日目标
     */
    @RequiresPermissions("tpAnalysisDailyTargetSet:setDailyTarget")
    @PostMapping("/setDailyTarget")
    @ResponseBody
    public R setDailyTarget(HttpServletRequest request, @RequestParam Map<String, Object> params){

        try {
            //修改
            int res = tpAnalysisDailyTargetSetService.editDailyTarget(params);
            if(res>0){
                return R.ok("操作成功");
            }else{
                return R.error("操作失败，请稍后重试！");
            }
        }catch (AuthorizationException e){
            return R.error("操作失败，您没有操作权限！");
        }catch (Exception e){
            logger.error("设置日目标出错：",e.getMessage(),e);
            return R.error("操作失败，请稍后重试！");
        }

    }


    /**
     * 设置系数
     */
    @RequiresPermissions("tpAnalysisDailyTargetSet:setCoefficient")
    @PostMapping("/setCoefficient")
    @ResponseBody
    public R setCoefficient(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            int setType = Integer.parseInt(params.get("setType")+"");
            String yesSet = params.get("yesSet").toString();
            String noSet = params.get("noSet").toString();
            String dictNameYes = setType==0?"达成目标系数":"精品达成目标系数";
            String dictNameNo = setType==0?"未达成目标系数":"精品未达成目标系数";
            //修改
            int res1 = tpAnalysisDailyTargetSetService.updateYsDictByAnalysisDailyTargetCoefficient(dictNameYes,yesSet);
            int res2 = tpAnalysisDailyTargetSetService.updateYsDictByAnalysisDailyTargetCoefficient(dictNameNo,noSet);
            if(res1>0 && res2>0){
                return R.ok("操作成功");
            }else{
                return R.error("操作失败，请稍后重试！");
            }
        }catch (AuthorizationException e){
            return R.error("操作失败，您没有操作权限！");
        }catch (Exception e){
            logger.error("设置日目标系数出错：",e.getMessage(),e);
            return R.error("操作失败，请稍后重试！");
        }

    }



}